(function(angular) {
	'use strict';
	angular.module('fs.waf').controller('cda.lookup.intIndexActivateController', intIndexActivateController);
	intIndexActivateController.$inject = [ '$scope', '$q', '$uibModalInstance', 'Constants', 'dialogsModule', 'gridService', 'modalService', 'layoutConfig', 'validatorConfig', 'authService', 'intindexService'];
	function intIndexActivateController($scope, $q, $uibModalInstance, Constants, dialogsModule, gridService, modalService, layoutConfig, validatorConfig, authService, intindexService) {
		var ctrl = this, log = $scope.loggerFactory.getLogger("intindexhistory");
		ctrl.dialogsModule = dialogsModule;
		ctrl.layoutConfig = layoutConfig;
		ctrl.validatorConfig = validatorConfig;
		var selectedRows = dialogsModule.params.selectedRows;
		/*ctrl.ok = function() {
			$uibModalInstance.close();
		};*/
		ctrl.close = function() {
			$uibModalInstance.dismiss([]);
		};
		
		ctrl.init = function() {
			ctrl.gridOptions = gridService.createGridOptions($scope,
					ctrl.layoutConfig.tableConfigs.table, paginationChanged,
					rowSelectionChanged, sortChanged);
			ctrl.gridOptions.data = 'vm.searchCriteria.list';
			ctrl.searchCriteria = ctrl.gridOptions.defaultSearchCriteria;
			
			intindexService.initOptions(ctrl);
			
			ctrl.search();
		};
		
		ctrl.search = function() {
			ctrl.searchCriteria.list = [];
			authService.search(ctrl.searchCriteria).then(
			function(response) {
				angular.merge(ctrl.searchCriteria, response.data);
				gridService.updateGridOptions(ctrl.searchCriteria, ctrl.gridOptions);
			},angular.noop);
		};
		
		ctrl.intindexActivate = function(){
			if (!ctrl.selectedRows || ctrl.selectedRows.length == 0) {
				modalService.openErrorDialogs({
					messages : [ 'title.dialogs.info.norecsel' ]
				});
				return;
			}
			return authService.intindexActivate(ctrl.selectedRows[0]).then(saveSuccessful, saveFailed);
		};
		
		function saveSuccessful(response) {
			ctrl.close();
			dialogsModule.btnCallback['ok']();
		}

		function saveFailed(response) {
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}

		function paginationChanged(pageNum, pageSize) {
			ctrl.searchCriteria.pageNum = pageNum;
			ctrl.searchCriteria.pageSize = pageSize;
			ctrl.searchCriteria.list = [];
			ctrl.search();
		}

		function rowSelectionChanged(eventRow, selectedRows) {
			ctrl.selectedRows = selectedRows;
		}

		function sortChanged(sortColumns) {
			// now just support sort by one column
			ctrl.searchCriteria.sortDirection = sortColumns[0] ? sortColumns[0].direction : '';
			ctrl.searchCriteria.sortBy = sortColumns[0] ? sortColumns[0].sortBy : '';
			ctrl.search();
		}
	}
})(angular);
